import { useEffect, useState } from "react";
import styles from './index.less';
import {utils, ecvrf, sortition} from 'vrf.js';
import { Input, Button, message } from "antd";

const [publicKey, privateKey] = utils.generatePair();
console.log(`## publicKey=${publicKey}, privateKey=${privateKey}`);

export default () => {
    const [x, setX] = useState<string>('');

    const [value, setValue] = useState<any>();

    const [proof, setProof] = useState<any>();

    useEffect(() => {
        makeFirstLettersColored('title', ['#1ba805', '#f0486f', '#1876ff']);


        // const prizeIndex = mapVRFToRange(value, 100); // 结果：0-99
        // console.log(`抽中奖品索引：${prizeIndex}`);
    }, []);

    function mapVRFToRange(vrfOutput: any, maxNumber: number) {
        const bigIntValue = uint8ArrayToBigInt(vrfOutput);
        return bigIntValue % BigInt(maxNumber); // 映射到0-99
    }

    function uint8ArrayToBigInt(arr: any) {
        let result = 0n;
        for (const byte of arr) {
          result = (result << 8n) + BigInt(byte);
        }
        return result;
      }

    return (
        <div className={styles.root}>
            <p id='title' className={styles.title}>Verifiable Random Function</p>
            <div className={styles.content}>
                <div className={styles.vrf}>
                    <p className={styles.subTitle}>生成与验证</p>

                    <Input addonBefore='唯一标识' value={x} onChange={(e) => {
                        setX(e.target.value);
                    }} />

                    <Button className={styles.generate} onClick={() => {
                        const X = Buffer.from(x);
                        const {value, proof} = ecvrf.vrf(publicKey, privateKey, X);
                        setValue(value);
                        setProof(proof);
                    }}>生成</Button>

                    <Input addonBefore='生成结果' value={value} onChange={(e) => {
                        setValue(e.target.value);
                    }} />

                    <Button className={styles.verify} onClick={() => {
                        const X = Buffer.from(x);
                        const verify = ecvrf.verify(publicKey, X, proof, value);
                        if (verify) {
                            message.success('验证成功');
                        } else {
                            message.error('验证失败');
                        }
                    }}>验证</Button>
                </div>

                <div className={styles.sortition}>
                    <p className={styles.subTitle}>公平抽奖</p>
                </div>
            </div>
        </div>
    );
}

// 定义一个函数，传入 p 元素的 id 和颜色数组
const makeFirstLettersColored = (pId: string, colors: string[]): void => {
    // 获取指定 id 的 p 元素
    const pElement = document.getElementById(pId);
    if (!pElement) {
      console.error(`Element with id ${pId} not found`);
      return;
    }
  
    // 获取元素的文本内容并分割成单词数组
    const words = pElement.textContent?.trim().split(/\s+/) || [];
    if (words.length === 0) {
      return;
    }
  
    // 处理每个单词，将首字母设置为对应颜色数组中的颜色
    let modifiedHTML = '';
    const colorCount = colors.length;
    words.forEach((word, index) => {
      if (word.length > 0) {
        const firstLetter = word.charAt(0);
        const restOfWord = word.slice(1);
        // 使用颜色数组中的颜色，循环使用颜色
        const colorIndex = index % colorCount;
        const currentColor = colors[colorIndex];
        modifiedHTML += `<span><span style="color: ${currentColor};">${firstLetter}</span>${restOfWord}</span>`;
        // 添加空格，除非是最后一个单词
        if (index < words.length - 1) {
          modifiedHTML += ' ';
        }
      }
    });
  
    // 将修改后的内容设置回 p 元素
    pElement.innerHTML = modifiedHTML;
};